package com.bsj.travel.security.service;

import com.alibaba.fastjson2.JSON;
import com.bsj.travel.cached.redis.RedisCached;
import com.bsj.travel.constant.Constants;
import com.bsj.travel.def.common.VO.TokenUser;
import com.bsj.travel.def.global.JsonResultEnum;
import com.bsj.travel.exception.ApiException;
import com.bsj.travel.util.ServletUtils;
import com.bsj.travel.util.StringUtils;
import com.bsj.travel.util.ip.IpUtils;
import com.bsj.travel.util.uuid.IdUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author yinhao
 * @version 1.0
 * @description token验证处理
 * @date 2023/11/3
 */
@Component
@Slf4j
public class TokenService {

    @Autowired
    private RedisCached redisCached;

    /**
     * 创建登录令牌
     *
     * @param tokenUser
     * @return
     */
    public Map<String, Object> createToken(TokenUser tokenUser) {
        String uuid = IdUtils.fastUUID();
        tokenUser.setToken(uuid);
        tokenUser.setUserId(tokenUser.getSystemUser().getUserId());
        tokenUser.setUserName(tokenUser.getSystemUser().getUserName());
        tokenUser.setIpAddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
        //缓存令牌并设置有效期
        String userKey = Constants.LOGIN_TOKEN_KEY + uuid;
        //保存1天
        int expireTime = 60 * 60 * 24;
        redisCached.expire(userKey, JSON.toJSONString(tokenUser), expireTime);
        return Map.of("tokenUser", tokenUser);
    }

    /**
     * 删除用户缓存信息
     *
     * @param token
     */
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            redisCached.del(Constants.LOGIN_TOKEN_KEY + token);
        }
    }

    /**
     * 获取登录用户信息
     *
     * @param token
     * @return
     */
    public TokenUser getLoginUser(String token) {
        String tokenStr = redisCached.get(Constants.LOGIN_TOKEN_KEY + token);
        TokenUser tokenUser = JSON.parseObject(tokenStr, TokenUser.class);
        if (tokenUser == null) {
            throw new ApiException(JsonResultEnum.USER_LOGIN_AUTH_NULL);
        }
        return tokenUser;
    }
}
